<?php

namespace App\Console\Commands\ES;

use Illuminate\Contracts\Events\Dispatcher;
use Laravel\Scout\Console\ImportCommand;
use Laravel\Scout\Events\ModelsImported;

class ESImport extends ImportCommand
{
    /**
     * The name and signature of the console command.
     * @example php artisan es:import "App\Models\SysArticle" --tableCount=4
     * @var string
     */
    protected $signature = 'es:import {model : Class name of model to bulk import} {--tableCount= : The number of table count}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'es import split model';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @param Dispatcher $events
     * @return int
     */
    public function handle(Dispatcher $events)
    {
        $tableCount = $this->option('tableCount') ? : 4;
        $class = $class = $this->argument('model');
        try {
            for ($i = 0; $i < $tableCount; $i++) {
                $tableName = $class::tableName() . $i;
                $model = new $class;
                $model = $model->setTable($tableName);

                $events->listen(ModelsImported::class, function ($event) use ($class) {
                    $key = $event->models->last()->getScoutKey();

                    $this->line('<comment>Imported ['.$class.'] models up to ID:</comment> '.$key);
                });
                $model::makeAllSearchable($i);
                $events->forget(ModelsImported::class);
            }
        } catch (\Exception $e) {
            //dd($e->getTrace());
            $this->warn("ERROR : ".$e->getCode() . ' - ' .$e->getMessage());
            return 0;
        }

        $this->info('All ['.$class.'] records have been imported.');
        return 0;
    }
}
